#!/usr/bin/env python
#-*- coding:utf-8 -*-

"""
	PROJECT pyevocomm -

	APP 	socket client controller

	MODULE	Arduino

	SITE DESCRIPTION http://code.google.com/p/pyevocomm/ 

	@copyright: 2012 by archetipo <alessio.gerace@gmail.com>
	@license: New BSD License, see COPYING for details.
"""

import serial
import utils
from socket import *
import threading
import json

Host_server = "19.61.1.1" # L'host del server in questo caso corrisponde al localhost poiché stiamo lavorado in locale, ma cambierà a seconda della posizione del server in ascolto
Port_server = 4001
    
class Arduino():
    def __init__(self,Port='/dev/ttyUSB0',Boud=115200,connState=0): 
        self.parent=self
        self.port=Port
        self.boud=Boud
        self.connState=connState
        self.timeount=1
        self.ser=None
        self.connect()
    def connect(self): 
        try:
            self.ser=serial.Serial(self.port,self.boud,timeout=0.0001)
            self.connState=1
            return [1,'connect']
        except:
            self.connState=0
            return [0,'no hardware found']
    
    
    def loadData(self):		
        self.buffer=self.ser.read(1)        
        if (self.buffer<>''):
			client = socket(AF_INET, SOCK_STREAM)
			client.connect((Host_server, Port_server)) 			
			if self.buffer=='d': 
				value=utils.datacom.datrigth
			elif self.buffer=='l': 
				value=utils.datacom.datleft
			elif self.buffer=='u': 
				value=utils.datacom.datsingle
			elif self.buffer=='i': 
				value=utils.datacom.datlang
			elif self.buffer=='c': 
				value=utils.datacom.datclose
			elif self.buffer=='s': 
				value=utils.datacom.datselect
			elif self.buffer=='p': 
				value=utils.datacom.datlang            
			elif self.buffer=='n': 
				value=utils.datacom.datstep            
			elif self.buffer=='f': 
				value=utils.datacom.datinsel            
			elif self.buffer=='z': 
				value=utils.datacom.datlost
			elif self.buffer=='m': 
				value=utils.datacom.datmenu
			else:
				value=utils.datacom.datnos
			j=json.dumps(value)
			client.send(j) 

ard=Arduino()
while True:
	ard.loadData()
